package cloud.xlh.infrastructure.utils;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.InetSocketAddress;
import java.net.Socket;

/**
 * Created with IntelliJ IDEA.
 *
 * @ project name : xlh_osms
 * @ Author: XuLeHuang
 * @ Date: 2023/2/21 17:12
 * @ Description:
 */
public class TcpClient {

    public String send(String data , String ip , int port , String encoding , int msgLen) {
        byte[] req = null;
        try {
            req = data.getBytes(encoding);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        Socket client = new Socket();
        try {
            client.setSoTimeout(2000);
            client.connect(new InetSocketAddress(ip , port));
        } catch (IOException e) {
            e.printStackTrace();
        }
        OutputStream outputStream = null;
        try {
            outputStream = client.getOutputStream();
           String len = "";
           len = String.format("%0" + msgLen + "d", req.length);
            outputStream.write(len.getBytes(encoding));
            outputStream.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
        InputStream inputStream = null;
        try {
            inputStream = client.getInputStream();
            byte[] resLen = new byte[msgLen];
            inputStream.read(resLen);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return "";
    }


    public static void main(String[] args) {
        System.out.println(String.format("0%" + 4 + "d", 5));
    }
}
